# -*- encoding: utf-8 -*-
'''
@File    :   routingtable.py
@Time    :   2021/06/22 09:42:24
@Author  :   Tan yunlin 
@Version :   1.0
@Contact :   3465126952@qq.com
@Desc    :   路由表的实现
'''

# here put the import lib
import math
import time
import timeit
import secrets
import matplotlib.pyplot as plt
from numpy.lib.function_base import average
from kbucket import KBucket
from node import Node


class RoutingTable:
    """
        每个节点都需要维护自己的路由表，路由表就是KBucket列表，
        距离该节点不同距离的节点会被存储在不同的k桶里
    """
    def __init__(self, node, nodes, ksize, bucket_length):
        """
         @node代表该路由表的拥有者
         @nodes代表全部的nodes
         @ksize代表每个k桶的最大容量
         @bucket_length代表路由表有多少个k桶
        """
        self.node = node
        self.nodes = nodes
        self.init_table(ksize, bucket_length)
        self.kszie = ksize

    def init_table(self, ksize, bucket_length):
        """
         路由表初始化
         @ksize：k桶大小
         @bucket_lenght：k桶的长度
        """
        self.KBuckets = []
        for i in range(bucket_length):
            kbucket = KBucket(2**i, 2**(i + 1), ksize)
            self.KBuckets.append(kbucket)

    def build_table(self, node, nodes, ksize):
        """
        路由表建立
        @node：路由表的拥有节点
        @nodes:所有节点
        @ksize：k桶大小
        """
        for addnode in nodes:
            if (addnode != node):
                distance = node.distance_to(addnode)
                for KBucket in self.KBuckets:
                    if (KBucket.range[0] <= distance < KBucket.range[1]
                            and len(KBucket.bucket) <= ksize):
                        KBucket.add_node(addnode)
        print("node：" + str(node.id) + "路由表建立成功！")

    def print_table(self):
        """
        路由表打印
        """
        i = 1
        for KBucket in self.KBuckets:
            print(str(i) + ":")
            print(KBucket.bucket)
            i += 1
        print("=======over========")


def main(ksize, node_num, d):
    # ksize = 14
    # node_num = 10
    bucket_length = 40  # 也代表node_id的bit数
    nodes = []

    # 固定节点 100个
    # rids = [
    #     736019761295, 683758072210, 103825834232, 105454225121, 688857824278,
    #     429507564851, 478280347247, 114554725514, 755262030526, 1065775146273,
    #     287414033957, 776310991527, 610655516924, 119799885970, 810017298094,
    #     146489799497, 993254855918, 63768334978, 268377971456, 716569034673,
    #     239465334000, 886451604512, 637675786717, 921136789561, 465628219090,
    #     94150968944, 899707204157, 425990992567, 547960628515, 194197676686,
    #     1010518565546, 653728311907, 1083273775936, 772977753219, 788416420643,
    #     108154530982, 2717493255, 626461705116, 404398881264, 472607350209,
    #     238288174322, 636284663033, 892757304452, 835065536884, 18476914130,
    #     726914931690, 130223879538, 205473735143, 167474419854, 956790237541,
    #     594853231961, 730341545692, 907877719003, 668423413616, 422138961667,
    #     228611913868, 368821043447, 1015837726979, 29799426063, 816865401537,
    #     586421791429, 663648596591, 387359970206, 347604945277, 365027835966,
    #     656464535241, 1083435463528, 900165734072, 953672147063, 56150301955,
    #     540271016011, 921252468567, 809709152666, 673377053668, 244138813832,
    #     1016671441013, 956745938775, 928496608559, 976609771434, 916821926404,
    #     105380759923, 476554511751, 1058006020551, 531867179985, 21911897514,
    #     15773570407, 309056530598, 440841750646, 818695401658, 492680523070,
    #     706241375811, 250313362913, 1029194578024, 592455845203, 852105399331,
    #     1049215258433, 1009832594771, 739017890177, 1089949032501, 471507250861
    # ]

    # 固定节点500个
    rids = [
        895305797019, 178102521574, 382896899724, 73787998050, 965756443268,
        83848642077, 922266796028, 545321258318, 555935966991, 524399826633,
        742458439561, 632149164820, 632594262640, 952098245209, 778132690411,
        477065454270, 529310026873, 456749086987, 615519528037, 993711137204,
        339435503406, 153855160313, 137396445841, 688076710543, 504460367563,
        696852877554, 769292822986, 70917351347, 447749997464, 114013964479,
        209642308664, 572275071269, 102008248328, 872230052017, 253504952,
        182667098766, 1026485745149, 742942075282, 347554332266, 3322790945,
        337017813192, 1030690245719, 316858338617, 809345292414, 1092260228407,
        539158047176, 100701096154, 30446215955, 856643770119, 27857249734,
        1035507648753, 486018065084, 423739837742, 1091512141875, 252808416368,
        889738838292, 391604507572, 261312973149, 420678940856, 902738338352,
        867728771151, 936952442816, 642401833604, 217948288151, 951517587718,
        351156645753, 1088919558835, 319953079850, 812233669309, 417880470950,
        891491637762, 152933769212, 996839257093, 981161063282, 219498233181,
        408259811539, 356599409114, 679461799879, 918511755592, 1067717259273,
        739003827429, 1071794762600, 668814317379, 66109972307, 657331207970,
        632440123967, 333207636636, 210005361450, 1040413084088, 426219761981,
        122692858362, 182468915963, 165852958868, 355017947068, 692519883696,
        270235654187, 918719871171, 606308917314, 177674677638, 379851949069,
        135179644176, 110278768319, 392943412192, 987580509398, 256289003453,
        764968055832, 984674367363, 445917623958, 329677157087, 339734414181,
        198939575424, 22101209160, 488988863561, 300400903813, 878935238618,
        237504758738, 653957711851, 162514330580, 244434440896, 40109195616,
        292514510611, 776496124036, 1029363495472, 613577584322, 993300274815,
        989282932065, 131224289465, 71724490559, 963772752881, 153505608017,
        1022864195101, 181139794562, 924064048629, 128273993973, 719585271924,
        527684671477, 433039761884, 48662271468, 400157934903, 901099838637,
        342778118714, 1043105704459, 647587844762, 299187234908, 497648837968,
        979794520785, 323211136219, 717095381873, 294539718753, 549924740647,
        544426247083, 461106756083, 824951792941, 989525142282, 974780636782,
        220601428829, 360400306897, 92351958004, 44899106164, 859702290679,
        683222358509, 985944317427, 744607674277, 154300859348, 163541875985,
        949427200945, 790781712663, 777474383914, 374837056319, 1064654346175,
        349971659639, 795357956780, 200060629630, 997039634851, 572387155871,
        899605328952, 400887377338, 740643858747, 851839770375, 590352203863,
        733976546285, 391245765510, 431750875509, 296270475404, 804229399288,
        1055418239836, 845061103748, 425431969564, 250639734811, 1040686704514,
        499622769417, 813400192186, 385797450142, 297745412064, 625554418296,
        475580609027, 869777540596, 714224158656, 158407630186, 133804585413,
        426106946818, 537843370768, 648694996540, 390649323272, 580733809408,
        18006390902, 419820069841, 1033375128436, 10617225181, 1005829992235,
        577710155219, 746254986218, 103837515259, 125002760076, 537566658272,
        1067056504189, 363482539351, 128848339420, 328984411673, 808870144609,
        400347445394, 266652813524, 484976517666, 312196522495, 454375900032,
        157466143346, 342176744959, 1067613412822, 451881698278, 878786605230,
        966594974143, 176205130524, 424944095879, 541839022429, 801953606426,
        678932942496, 834383114876, 946890841010, 774367153984, 514004909850,
        563625324631, 1044888018335, 101041280508, 147017669085, 67735238345,
        431396377753, 1000812291665, 531595187451, 91728626864, 585348825491,
        618200270153, 578232893862, 152430936130, 834610245680, 788035160519,
        927387276356, 139289533826, 131547887721, 603598891893, 605206839964,
        20499674506, 694037466204, 497819736168, 635342175017, 84294932797,
        333909296825, 434141649071, 913526049229, 764905263515, 1092433826035,
        866808317495, 208233308378, 970601440390, 928368691301, 745503707381,
        134448570457, 1026645845494, 540481732725, 624281684581, 582221839556,
        486354466290, 445325483734, 983731017009, 619755449416, 1040656107514,
        796807225961, 856329679265, 868071668809, 995021590986, 756231452728,
        637589516142, 446413749140, 519457319507, 544743552420, 318155892552,
        909128414153, 871352982649, 892654705138, 343791222268, 464156454340,
        774772749338, 726236348944, 485225359599, 931435512622, 427185445559,
        825800179915, 900722753537, 934124496576, 725704546283, 722341876807,
        712043506236, 1064123745166, 67032132343, 291691726180, 115177472462,
        1043790147962, 799519001525, 1035925605890, 570786221375, 131890675416,
        92456847648, 930735555081, 212614687662, 1096387250995, 380730474447,
        391431002218, 45644570717, 260204841639, 152827302832, 713317662959,
        1035785890033, 790407714434, 866399849276, 950683759005, 309425859768,
        407456616919, 192214114120, 531853667579, 539667600525, 445672770644,
        1093910804038, 687423257702, 339448586950, 566589075793, 281866864357,
        334888542470, 604899478017, 328648008924, 218927034307, 656157893775,
        381070647819, 946532387115, 1090606821185, 1075433934839, 736350326138,
        96232790187, 857646188168, 1078277386111, 343953097838, 84571809037,
        641276305077, 275937451428, 734695308502, 848798946845, 454501560304,
        21364238430, 556843148392, 193804715809, 556534877323, 271584897567,
        638202434459, 366161739758, 346017709904, 293021577661, 518930559606,
        496498349998, 259707929808, 1064294179579, 1050676641953,
        1017708108276, 335646659423, 676485796930, 389667297535, 673397069907,
        267982487566, 229714653339, 727726721700, 501538806211, 899998002127,
        14645254465, 43674457838, 287410379798, 853742300744, 437637152204,
        807790507937, 85134132990, 498973536211, 492787481931, 747920656214,
        695230553176, 329798656602, 463096198742, 760108472934, 970302909600,
        634304913888, 597558653664, 648580802066, 569601071642, 457564115435,
        854437321883, 106013750243, 603164685205, 2098566621, 961590018220,
        49007052285, 236942739991, 144847469003, 796458139311, 24155281490,
        671836803104, 471360694046, 60375203599, 979519420788, 1064587565700,
        410297875468, 591258593900, 734727477230, 1000939401277, 944338445403,
        19330042439, 1067446448895, 1059854623843, 89111696238, 1054444319736,
        965050221759, 1029672519891, 38666795251, 396773191999, 638153722696,
        855783455033, 280229278479, 220480585242, 635553411866, 770708542843,
        65436762173, 1087886573196, 345458466865, 218002490225, 756927312828,
        590619573701, 966605096835, 1006267496964, 1025068805045, 4675879341,
        950844769293, 286122660404, 448055088474, 217306981507, 727394190421,
        921979968629, 80379621556, 842109573470, 150960142117, 745199830726,
        533588822696, 367680527968, 154612085757, 644073167940, 1098914708686,
        31626107229, 1054510139697, 987822153123, 913466530250, 733331264402,
        1009748711097, 882947539264, 666918734714, 364511577671, 666100496283,
        258538554142, 323491065181, 998435110475, 1061040995404, 894573116204,
        825988466815, 688188515047, 733986882901, 153135377540, 676726939490,
        785082871061, 140277448745, 652433795481, 993497177523, 763054129496,
        398982043944, 532782351561, 165633831383, 491223332047, 94579965243,
        850749552884
    ]

    # 获得固定数量节点
    for i in range(node_num):
        rid = rids[i]
        node = Node(rid)
        nodes.append(node)

    # 获得安全的随机数生成器
    secretsGenerator = secrets.SystemRandom()
    #  随机生成动态节点
    # rids = []
    # for i in range(node_num):
    #     rid = secrets.randbits(bucket_length)  # 生成bucket_length bit的安全随机数
    #     print(",", rid)
    #     rids.append(rid)
    #     node = Node(rid)
    #     nodes.append(node)
    # print(len(rids))

    routingtables = []
    for i in range(node_num):
        routingtable = RoutingTable(nodes[i], nodes, ksize, bucket_length)
        routingtable.build_table(nodes[i], nodes, ksize)
        # routingtable.print_table()
        routingtables.append(routingtable)

    # 实验：DHT的路由表，当K桶取不同值时，对通信开销的影响
    #1. 车辆数不变，即节点数量不变， k值变化对单个节点平均通信开销影响
    # d = 2**30  #代表通信距离
    endIndex = int(math.log2(d)) - 1  # 代表需要遍历的k通终止下标
    time0 = timeit.default_timer()
    for routingtable in routingtables:
        Kbuckets_list = routingtable.KBuckets
        for i in range(endIndex + 1):
            count = Kbuckets_list[i].get_length()
            while count:
                # 模拟延时
                time.sleep(secretsGenerator.uniform(0, 0.005))
                count -= 1
    return timeit.default_timer() - time0


def main2():
    """
    实验5目的：测试使用DHT和不是用DHT时通信开销对比
    设置节点数从10-50
    d=2^30
    K=11 
    """
    # 测试DHT的情况下所有节点总的开销
    DHTresults = []
    for node_num in range(10, 60, 10):
        DHTresult = main(11, node_num, 2**30)
        DHTresults.append(DHTresult)

    for DHTresult in DHTresults:
        print(DHTresult)


def Broadcast():
    """
    按广播模式进行计算
    """
    nodes = []
    # 固定节点500个
    rids = [
        895305797019, 178102521574, 382896899724, 73787998050, 965756443268,
        83848642077, 922266796028, 545321258318, 555935966991, 524399826633,
        742458439561, 632149164820, 632594262640, 952098245209, 778132690411,
        477065454270, 529310026873, 456749086987, 615519528037, 993711137204,
        339435503406, 153855160313, 137396445841, 688076710543, 504460367563,
        696852877554, 769292822986, 70917351347, 447749997464, 114013964479,
        209642308664, 572275071269, 102008248328, 872230052017, 253504952,
        182667098766, 1026485745149, 742942075282, 347554332266, 3322790945,
        337017813192, 1030690245719, 316858338617, 809345292414, 1092260228407,
        539158047176, 100701096154, 30446215955, 856643770119, 27857249734,
        1035507648753, 486018065084, 423739837742, 1091512141875, 252808416368,
        889738838292, 391604507572, 261312973149, 420678940856, 902738338352,
        867728771151, 936952442816, 642401833604, 217948288151, 951517587718,
        351156645753, 1088919558835, 319953079850, 812233669309, 417880470950,
        891491637762, 152933769212, 996839257093, 981161063282, 219498233181,
        408259811539, 356599409114, 679461799879, 918511755592, 1067717259273,
        739003827429, 1071794762600, 668814317379, 66109972307, 657331207970,
        632440123967, 333207636636, 210005361450, 1040413084088, 426219761981,
        122692858362, 182468915963, 165852958868, 355017947068, 692519883696,
        270235654187, 918719871171, 606308917314, 177674677638, 379851949069,
        135179644176, 110278768319, 392943412192, 987580509398, 256289003453,
        764968055832, 984674367363, 445917623958, 329677157087, 339734414181,
        198939575424, 22101209160, 488988863561, 300400903813, 878935238618,
        237504758738, 653957711851, 162514330580, 244434440896, 40109195616,
        292514510611, 776496124036, 1029363495472, 613577584322, 993300274815,
        989282932065, 131224289465, 71724490559, 963772752881, 153505608017,
        1022864195101, 181139794562, 924064048629, 128273993973, 719585271924,
        527684671477, 433039761884, 48662271468, 400157934903, 901099838637,
        342778118714, 1043105704459, 647587844762, 299187234908, 497648837968,
        979794520785, 323211136219, 717095381873, 294539718753, 549924740647,
        544426247083, 461106756083, 824951792941, 989525142282, 974780636782,
        220601428829, 360400306897, 92351958004, 44899106164, 859702290679,
        683222358509, 985944317427, 744607674277, 154300859348, 163541875985,
        949427200945, 790781712663, 777474383914, 374837056319, 1064654346175,
        349971659639, 795357956780, 200060629630, 997039634851, 572387155871,
        899605328952, 400887377338, 740643858747, 851839770375, 590352203863,
        733976546285, 391245765510, 431750875509, 296270475404, 804229399288,
        1055418239836, 845061103748, 425431969564, 250639734811, 1040686704514,
        499622769417, 813400192186, 385797450142, 297745412064, 625554418296,
        475580609027, 869777540596, 714224158656, 158407630186, 133804585413,
        426106946818, 537843370768, 648694996540, 390649323272, 580733809408,
        18006390902, 419820069841, 1033375128436, 10617225181, 1005829992235,
        577710155219, 746254986218, 103837515259, 125002760076, 537566658272,
        1067056504189, 363482539351, 128848339420, 328984411673, 808870144609,
        400347445394, 266652813524, 484976517666, 312196522495, 454375900032,
        157466143346, 342176744959, 1067613412822, 451881698278, 878786605230,
        966594974143, 176205130524, 424944095879, 541839022429, 801953606426,
        678932942496, 834383114876, 946890841010, 774367153984, 514004909850,
        563625324631, 1044888018335, 101041280508, 147017669085, 67735238345,
        431396377753, 1000812291665, 531595187451, 91728626864, 585348825491,
        618200270153, 578232893862, 152430936130, 834610245680, 788035160519,
        927387276356, 139289533826, 131547887721, 603598891893, 605206839964,
        20499674506, 694037466204, 497819736168, 635342175017, 84294932797,
        333909296825, 434141649071, 913526049229, 764905263515, 1092433826035,
        866808317495, 208233308378, 970601440390, 928368691301, 745503707381,
        134448570457, 1026645845494, 540481732725, 624281684581, 582221839556,
        486354466290, 445325483734, 983731017009, 619755449416, 1040656107514,
        796807225961, 856329679265, 868071668809, 995021590986, 756231452728,
        637589516142, 446413749140, 519457319507, 544743552420, 318155892552,
        909128414153, 871352982649, 892654705138, 343791222268, 464156454340,
        774772749338, 726236348944, 485225359599, 931435512622, 427185445559,
        825800179915, 900722753537, 934124496576, 725704546283, 722341876807,
        712043506236, 1064123745166, 67032132343, 291691726180, 115177472462,
        1043790147962, 799519001525, 1035925605890, 570786221375, 131890675416,
        92456847648, 930735555081, 212614687662, 1096387250995, 380730474447,
        391431002218, 45644570717, 260204841639, 152827302832, 713317662959,
        1035785890033, 790407714434, 866399849276, 950683759005, 309425859768,
        407456616919, 192214114120, 531853667579, 539667600525, 445672770644,
        1093910804038, 687423257702, 339448586950, 566589075793, 281866864357,
        334888542470, 604899478017, 328648008924, 218927034307, 656157893775,
        381070647819, 946532387115, 1090606821185, 1075433934839, 736350326138,
        96232790187, 857646188168, 1078277386111, 343953097838, 84571809037,
        641276305077, 275937451428, 734695308502, 848798946845, 454501560304,
        21364238430, 556843148392, 193804715809, 556534877323, 271584897567,
        638202434459, 366161739758, 346017709904, 293021577661, 518930559606,
        496498349998, 259707929808, 1064294179579, 1050676641953,
        1017708108276, 335646659423, 676485796930, 389667297535, 673397069907,
        267982487566, 229714653339, 727726721700, 501538806211, 899998002127,
        14645254465, 43674457838, 287410379798, 853742300744, 437637152204,
        807790507937, 85134132990, 498973536211, 492787481931, 747920656214,
        695230553176, 329798656602, 463096198742, 760108472934, 970302909600,
        634304913888, 597558653664, 648580802066, 569601071642, 457564115435,
        854437321883, 106013750243, 603164685205, 2098566621, 961590018220,
        49007052285, 236942739991, 144847469003, 796458139311, 24155281490,
        671836803104, 471360694046, 60375203599, 979519420788, 1064587565700,
        410297875468, 591258593900, 734727477230, 1000939401277, 944338445403,
        19330042439, 1067446448895, 1059854623843, 89111696238, 1054444319736,
        965050221759, 1029672519891, 38666795251, 396773191999, 638153722696,
        855783455033, 280229278479, 220480585242, 635553411866, 770708542843,
        65436762173, 1087886573196, 345458466865, 218002490225, 756927312828,
        590619573701, 966605096835, 1006267496964, 1025068805045, 4675879341,
        950844769293, 286122660404, 448055088474, 217306981507, 727394190421,
        921979968629, 80379621556, 842109573470, 150960142117, 745199830726,
        533588822696, 367680527968, 154612085757, 644073167940, 1098914708686,
        31626107229, 1054510139697, 987822153123, 913466530250, 733331264402,
        1009748711097, 882947539264, 666918734714, 364511577671, 666100496283,
        258538554142, 323491065181, 998435110475, 1061040995404, 894573116204,
        825988466815, 688188515047, 733986882901, 153135377540, 676726939490,
        785082871061, 140277448745, 652433795481, 993497177523, 763054129496,
        398982043944, 532782351561, 165633831383, 491223332047, 94579965243,
        850749552884
    ]
    Broad_results = []
    # 获得安全的随机数生成器
    secretsGenerator = secrets.SystemRandom()
    # 获得固定数量节点10，20，30，40，50
    for node_num in range(10, 60, 10):
        for i in range(node_num):
            rid = rids[i]
            node = Node(rid)
            nodes.append(node)
        print("node_num=:", node_num)
        time0 = timeit.default_timer()
        for every_node in nodes:
            for other in nodes:
                if every_node != other:
                    # 模拟延时
                    time.sleep(secretsGenerator.uniform(0, 0.005))
        Broad_result = (timeit.default_timer() - time0) / 2.0
        Broad_results.append(Broad_result)
    # 输出结果
    for Broad_result in Broad_results:
        print(Broad_result)


if __name__ == "__main__":
    # Broadcast()
    main2()
    # 实验3目的：测试不同K值对通信开销的影响K=1~20
    # averagetimes = [0.0] * 20
    # # 测试100次，取平均值
    # for x in range(20):
    #     # K值从1取到20
    #     for i in range(1, 21):
    #         runtime = main(i, 500,2**30)
    #         averagetimes[i - 1] += runtime
    # for i in range(20):
    #     averagetimes[i] /= 20.0
    # for averagetime in averagetimes:
    #     print(averagetime)

    # 实验4目的：在最优K=11的情况下，不同节点时d值对通信开销的影响，d=2^10~2^30
    # results = []
    # for index in range(1, 40):
    #     d = math.pow(2, index)
    #     # print("index=" + str(index) + " d=:" + str(d))
    #     result = main(11, 100, d)
    #     results.append(result)
    # for result in results:
    #     print(result)
    # 画图
    # plt.title("Different d for Communication Cost")
    # plt.xlabel("d")
    # plt.ylabel("Cost(s)")
    # plt.plot(range(1, 40), results)
    # plt.plot(range(1, 40), results, 'o')
    # plt.show()
